#!/bin/bash

# 生产环境部署脚本 - 包含完整的依赖安装
set -e

FRONTEND_PORT=7171
BACKEND_PORT=7172

echo "🚀 生产环境部署脚本..."

# 拉取最新代码
echo "📥 拉取最新代码..."
git pull || {
    echo "⚠️  Git pull 失败，继续执行..."
}

# 测试并重新加载nginx配置
echo "🔄 重新加载nginx配置..."
sudo nginx -t && sudo nginx -s reload || {
    echo "⚠️  Nginx配置重载失败，继续执行..."
}

# 停止所有 PM2 进程
echo "🛑 停止现有服务..."
pm2 stop all 2>/dev/null || true
pm2 delete all 2>/dev/null || true

# 强制清理端口占用
echo "🧹 清理端口占用..."
sudo fuser -k $FRONTEND_PORT/tcp 2>/dev/null || true
sudo fuser -k $BACKEND_PORT/tcp 2>/dev/null || true
sleep 2

# 构建并启动后端
echo "🔨 构建后端服务..."
cd backend

# 安装所有依赖（包括开发依赖，用于构建）
echo "📦 安装后端依赖（包括开发依赖）..."
pnpm install

# 重新生成Prisma客户端
echo "🔄 重新生成Prisma客户端..."
npx prisma generate

if [ $? -eq 0 ]; then
    echo "✅ Prisma客户端生成成功"
else
    echo "❌ Prisma客户端生成失败"
    exit 1
fi

# 运行数据库迁移
echo "🗄️ 运行数据库迁移..."
#npx prisma migrate deploy
npx prisma db push
if [ $? -eq 0 ]; then
    echo "✅ 数据库迁移成功"
else
    echo "❌ 数据库迁移失败"
    exit 1
fi

# 构建项目
echo "🔨 构建后端代码..."
pnpm run build

if [ ! -f "dist/src/main.js" ]; then
    echo "❌ 后端构建失败：main.js 不存在"
    exit 1
fi

echo "✅ 后端构建成功"

# 清理开发依赖（可选，节省空间）
echo "🧹 清理开发依赖..."
pnpm prune --prod || echo "⚠️  prune 失败，继续执行..."

# 启动后端服务
echo "🚀 启动后端服务..."
PORT=$BACKEND_PORT pm2 start npm --name "ignitefun-backend" -- run start:prod

sleep 3

# 构建并启动前端
echo "🔨 构建前端服务..."
cd ../frontend

# 安装依赖
echo "📦 安装前端依赖..."
pnpm install

# 构建前端
echo "🔨 构建前端代码..."
pnpm run build

if [ ! -d ".next" ]; then
    echo "❌ 前端构建失败：.next 目录不存在"
    exit 1
fi

echo "✅ 前端构建成功"

# 启动前端服务
echo "🚀 启动前端服务..."
PORT=$FRONTEND_PORT pm2 start npm --name "ignitefun-frontend" -- start

sleep 5

# 检查状态
echo "📊 检查服务状态..."
pm2 list

echo ""
echo "🔍 检查端口状态:"
echo "后端端口 $BACKEND_PORT:"
lsof -i:$BACKEND_PORT || echo "端口未被监听"

echo "前端端口 $FRONTEND_PORT:"
lsof -i:$FRONTEND_PORT || echo "端口未被监听"

echo ""
echo "🧪 测试服务响应:"
if curl -s http://localhost:$BACKEND_PORT/api/health > /dev/null; then
    echo "✅ 后端服务正常"
    echo "📄 健康检查: $(curl -s http://localhost:$BACKEND_PORT/api/health)"
else
    echo "❌ 后端服务异常"
    echo "📝 查看后端日志:"
    pm2 logs ignitefun-backend --lines 5
fi

if curl -s http://localhost:$FRONTEND_PORT > /dev/null; then
    echo "✅ 前端服务正常"
else
    echo "❌ 前端服务异常"
    echo "📝 查看前端日志:"
    pm2 logs ignitefun-frontend --lines 5
fi

echo ""
echo "🧪 测试WebSocket连接..."
websocket_response=$(curl -s -w "%{http_code}" http://localhost:$BACKEND_PORT/socket.io/?EIO=4&transport=polling -o /tmp/ws_test.txt 2>/dev/null || echo "failed")
if [ "$websocket_response" = "200" ]; then
    echo "✅ WebSocket端点正常"
else
    echo "❌ WebSocket端点异常: $websocket_response"
fi

echo ""
echo "🎉 部署完成！"
echo ""
echo "📋 部署总结："
echo "  - ✅ 代码已更新"
echo "  - ✅ 后端已完整构建（包含聊天功能）"
echo "  - ✅ 前端已构建"
echo "  - ✅ 服务已启动"
echo ""
echo "🌐 访问地址："
echo "  - 生产环境: https://c4pad.fun"
echo "  - 直接访问: http://104.129.59.158"
echo ""
echo "📝 日志查看："
echo "  - 后端: pm2 logs ignitefun-backend"
echo "  - 前端: pm2 logs ignitefun-frontend"
echo "  - 所有: pm2 logs"
